<script setup lang="ts">
import { computed, ref } from 'vue'
import { segmentHeight } from '@/utils/lib'
import { toPercent, toThousand } from '@/utils/filter'
import usePx2rempx from '@/hook/px2rempx'
import px2rem from '@/utils/flexble'
import { client } from '@/utils/http'
import { useQuery } from '@tanstack/vue-query'
import useFilterStore from '@/stores/filter'
import { storeToRefs } from 'pinia'
import { sumBy } from 'lodash-es'

const filterStore = useFilterStore()

const { ymdId, checkDataUpdateNum } = storeToRefs(filterStore)

const { data: overviewData, isFetching: overviewLoading } = useQuery<{
  stockMonth: number
  stockFreeQty: number
  stockGreat60Month: string
  surplusOrderQty: number
  undeliverOrderQty: number
  etlDt: string
  stockEtlDt: string
  orderEtlDt: string
  stockQty: number
  surplusOrderMonth: string
  stockInTransitQty: number
  stockInFactoryQty: number
  stock60Month: string
  surplusNotmatOrderQty: number
  matchOrderQty: number
  stockTotal: number
  matchRate: string
  unpaidOrderQty: number
  stock30Month: string
}>({
  keepPreviousData: true,
  queryKey: ['/saleCoreBoard/getStockData', ymdId, checkDataUpdateNum],
  queryFn: () => client('/saleCoreBoard/getStockData', { ymdId: ymdId.value }),
  enabled: computed(() => !!ymdId.value)
})

const { data: stockModelData, isFetching: stockModelLoading } = useQuery<{
  count: {
    stockGreat60Qty: number
    stock60Qty: number
    stock30Qty: number
  }
  list: {
    modelName: string
    stockGreat60Qty: number
    stock60Qty: number
    stock30Qty: number
    modelId: string
    logo: string
    longOrderQty: number
    sort: number
    matchRate: string
    [key: string]: string | number
  }[]
}>({
  keepPreviousData: true,
  queryKey: ['/saleCoreBoard/getStockModel', ymdId, checkDataUpdateNum],
  queryFn: () => client('/saleCoreBoard/getStockModel', { ymdId: ymdId.value }),
  enabled: computed(() => !!ymdId.value)
})

const { remPx: gutter } = usePx2rempx(8)

const overviewInventoryDatas = computed(() => {
  if (!overviewData.value) {
    return []
  }
  const { stockQty, stockInTransitQty, stockInFactoryQty, stockTotal } = overviewData.value
  return [
    {
      label: '总库存',
      value: toThousand(stockTotal)
    },
    {
      label: '店头库存',
      value: toThousand(stockQty)
    },
    {
      label: '在途库存',
      value: toThousand(stockInTransitQty)
    },
    {
      label: '未出厂',
      value: toThousand(stockInFactoryQty)
    }
  ]
})

const overviewOrderDatas = computed(() => {
  if (!overviewData.value) {
    return []
  }
  const { surplusOrderQty, surplusOrderMonth, matchRate } = overviewData.value
  return [
    {
      label: '剩余订单数',
      value: toThousand(surplusOrderQty)
    },
    {
      label: '剩余订单月数',
      value: surplusOrderMonth
    },
    {
      label: '匹配率',
      value: toPercent(matchRate, 1, false, '%', 1)
    }
  ]
})

const inventoryOrderDatas = computed(() => {
  if (!overviewData.value) {
    return []
  }
  const { stockFreeQty, surplusNotmatOrderQty } = overviewData.value
  return [
    {
      label: '自由库存',
      value: toThousand(stockFreeQty)
    },
    {
      label: `剩余订单<span style="color:rgba(255, 255, 255, 0.8);font-size:${px2rem(
        12
      )}">（未匹配）</span>`,
      value: toThousand(surplusNotmatOrderQty)
    }
  ]
})

const orderDatas = computed(() => {
  if (!overviewData.value) {
    return []
  }
  const {
    // stockFreeQty,
    // stockGreat60Month,
    undeliverOrderQty,
    // etlDt,
    // stock60Month,
    // surplusNotmatOrderQty,
    matchOrderQty,
    unpaidOrderQty
    // stock30Month
  } = overviewData.value
  return [
    {
      label: '匹配订单',
      value: toThousand(matchOrderQty)
    },
    {
      label: '未付款',
      value: toThousand(unpaidOrderQty)
    },
    {
      label: '未交车',
      value: toThousand(undeliverOrderQty)
    }
  ]
})

const inventoryType = ref('stockGreat60Qty')

const inventoryOptions = computed(() => {
  return [
    {
      value: 'stockGreat60Qty',
      label: '库龄 > 60天',
      num: toThousand(stockModelData.value?.count.stockGreat60Qty)
    },
    {
      value: 'stock60Qty',
      label: '30天 < 库龄 < 60天',
      num: toThousand(stockModelData.value?.count.stock60Qty)
    },
    {
      value: 'stock30Qty',
      label: '库龄 < 30天',
      num: toThousand(stockModelData.value?.count.stock30Qty)
    }
  ]
})

const showItemCount = 6

const carDatas2D = computed(() => {
  if (!stockModelData.value || !stockModelData.value.list) {
    return []
  }
  const datas2D = []
  let datas: any = []
  for (let index = 0; index < stockModelData.value.list.length; index++) {
    if (index % showItemCount === 0) {
      datas = []
      datas2D.push(datas)
    }
    const item = stockModelData.value.list[index]
    const {
      modelName,
      // stockGreat60Qty,
      // stock60Qty,
      // stock30Qty,
      modelId,
      logo
      // longOrderQty,
      // sort,
      // matchRate
    } = item
    datas.push({
      carId: modelId,
      carName: modelName,
      imgUrl: `http://ids-mobile.gtmc.com.cn/staticFile${logo}`,
      value: `${toThousand(item[inventoryType.value])}台`
    })
  }

  return datas2D
})

const rightShowItemCount = 3

const longCarNum = computed(() => {
  if (!stockModelData.value || !stockModelData.value.list) {
    return '-'
  }
  return toThousand(sumBy(stockModelData.value.list, (item) => Number(item.longOrderQty)))
})

const longCarDatas2D = computed(() => {
  if (!stockModelData.value || !stockModelData.value.list) {
    return []
  }
  const datas2D = []
  let datas: any = []
  for (let index = 0; index < stockModelData.value.list.length; index++) {
    if (index % rightShowItemCount === 0) {
      datas = []
      datas2D.push(datas)
    }
    const item = stockModelData.value.list[index]
    const { modelName, modelId, logo, longOrderQty } = item
    datas.push({
      carId: modelId,
      carName: modelName,
      imgUrl: `http://ids-mobile.gtmc.com.cn/staticFile${logo}`,
      value: `${toThousand(longOrderQty)}台`
    })
  }

  return datas2D
})

const rateCarDatas2D = computed(() => {
  if (!stockModelData.value || !stockModelData.value.list) {
    return []
  }
  const datas2D = []
  let datas: any = []
  for (let index = 0; index < stockModelData.value.list.length; index++) {
    if (index % rightShowItemCount === 0) {
      datas = []
      datas2D.push(datas)
    }
    const item = stockModelData.value.list[index]
    const { modelName, modelId, logo, matchRate } = item
    datas.push({
      carId: modelId,
      carName: modelName,
      imgUrl: `http://ids-mobile.gtmc.com.cn/staticFile${logo}`,
      value: toPercent(matchRate, 1, false, '%', 1)
    })
  }

  return datas2D
})
</script>

<template>
  <Segment
    :height="segmentHeight"
    title="库存情况"
    :right="`数据截止日期 库存: ${overviewData?.stockEtlDt || ''} 剩余订单: ${
      overviewData?.orderEtlDt || ''
    }`"
    :loading="overviewLoading || stockModelLoading"
  >
    <div class="inventory-status">
      <a-row :gutter="[gutter, gutter]" align="start">
        <a-col :span="9">
          <div class="bg right-arrow">
            <div class="overview">
              <div class="left-view">
                <div
                  class="item-values"
                  v-for="(overview, index) in overviewInventoryDatas"
                  :key="overview.label"
                >
                  <div class="label" :class="{ gray: index > 0 }">{{ overview.label }}</div>
                  <div class="value" :class="{ 'up-arrow': index === 1 }">{{ overview.value }}</div>
                </div>
              </div>
            </div>
            <div class="box">
              <div class="box-header">
                <div class="title">店头库存分布情况</div>
                <div class="right-value">
                  <div class="label">库存月数</div>
                  <div class="value">{{ toThousand(overviewData?.stockMonth) }}</div>
                </div>
              </div>
              <a-radio-group v-model:value="inventoryType" size="big" class="radio">
                <a-radio-button
                  v-for="option in inventoryOptions"
                  :key="option.value"
                  :value="option.value"
                >
                  <div class="label">{{ option.label }}</div>
                  <div class="num">{{ option.num }}</div>
                </a-radio-button>
              </a-radio-group>
              <div class="box-child">
                <CarCarousel :datas2D="carDatas2D" />
              </div>
            </div>
          </div>
        </a-col>
        <a-col :span="6">
          <div class="bg box-inventery-order">
            <div class="inventery-order-title">库存&订单分析</div>
            <div class="box-item">
              <div class="box-header">
                <div class="title">未匹配</div>
              </div>
              <div class="flex">
                <div class="item-values" v-for="data in inventoryOrderDatas" :key="data.label">
                  <div class="label" v-html="data.label"></div>
                  <div class="value">{{ data.value }}</div>
                </div>
              </div>
            </div>
            <div class="box-item">
              <div class="box-header">
                <div class="title">已匹配</div>
              </div>
              <div class="flex">
                <div class="item-values" v-for="(data, index) in orderDatas" :key="data.label">
                  <div class="label" :class="{ gray: index > 0 }">{{ data.label }}</div>
                  <div class="value">{{ data.value }}</div>
                </div>
              </div>
            </div>
          </div>
        </a-col>
        <a-col :span="9">
          <div class="bg left-arrow">
            <div class="overview">
              <div class="right-view">
                <div
                  class="item-values"
                  v-for="(overview, index) in overviewOrderDatas"
                  :key="overview.label"
                >
                  <div class="label">{{ overview.label }}</div>
                  <div class="value" :class="{ 'up-arrow': index === 2 }">{{ overview.value }}</div>
                </div>
              </div>
            </div>
            <a-row class="small-row" :gutter="[gutter, gutter]">
              <a-col :span="24">
                <div class="box">
                  <div class="box-header">
                    <div class="title">匹配率</div>
                  </div>
                  <div class="box-child">
                    <CarCarousel :datas2D="rateCarDatas2D" />
                  </div>
                </div>
              </a-col>
              <a-col :span="24">
                <div class="box">
                  <div class="box-header">
                    <div class="title">长期订单</div>
                    <div class="num">{{ longCarNum }}</div>
                  </div>
                  <div class="box-child">
                    <CarCarousel :datas2D="longCarDatas2D" />
                  </div>
                </div>
              </a-col>
            </a-row>
          </div>
        </a-col>
      </a-row>
    </div>
  </Segment>
</template>
<style lang="less" scoped>
.inventory-status {
  height: calc(100% - 32px);
  padding: 8px 16px 12px;
  .bg {
    position: relative;
    height: 100%;
    padding: 12px 12px 0;
    border-radius: 8px;
    background: linear-gradient(0deg, rgba(18, 38, 89, 0) -0.13%, rgba(11, 48, 120, 0.48) 99.87%);
    &.right-arrow {
      &::after {
        content: '';
        position: absolute;
        z-index: 9;
        top: 26px;
        right: -10px;
        width: 12px;
        height: 31px;
        background: url('@/assets/icons/inventory-right-arrow.svg') left no-repeat;
        background-size: contain;
      }
    }
    &.left-arrow {
      &::after {
        content: '';
        position: absolute;
        z-index: 9;
        top: 26px;
        left: -10px;
        width: 12px;
        height: 31px;
        background: url('@/assets/icons/inventory-left-arrow.svg') right no-repeat;
        background-size: contain;
      }
    }
  }
  .item-values {
    flex: 1;
    // display: flex;
    // flex-direction: column;
    // justify-content: space-between;
    .label {
      color: var(---, #fff);
      font-family: Alibaba PuHuiTi 2;
      font-size: 16px;
      font-style: normal;
      font-weight: 400;
      line-height: 21px;
      &.gray {
        font-size: 14px;
        color: #799bc0;
      }
    }
    .value {
      display: inline-block;
      position: relative;
      color: #fff;
      font-family: DIN Alternate;
      font-size: 24px;
      font-style: normal;
      font-weight: 700;
      line-height: normal;
      &.up-arrow {
        &::before {
          content: '';
          position: absolute;
          z-index: 9;
          left: calc(50%);
          bottom: calc(-11px - 16px + 10px);
          transform: translateX(-50%);
          width: 16px;
          height: 11px;
          background: url('@/assets/icons/inventory-up-arrow.svg') bottom no-repeat;
          background-size: contain;
        }
      }
    }
  }
  .overview {
    height: 54px;
    display: flex;
    align-items: center;
    gap: 36px;
    margin-bottom: 16px;
    .left-view,
    .right-view {
      flex: 1;
      display: flex;
      gap: 8px;
      justify-content: space-between;
    }
    .left-view {
      gap: 0;
      justify-content: flex-start;
      border-right: 1px solid rgba(4, 39, 128, 0.6);
      .item-values {
        position: relative;
        &::after {
          position: absolute;
          content: '+';
          top: 50%;
          right: 30px;
          color: #799bc0;
          font-family: Alibaba PuHuiTi 2;
          font-size: 14px;
          font-style: normal;
          font-weight: 700;
          line-height: 14px; /* 100% */
        }
        &:nth-child(1) {
          &::after {
            content: '=';
          }
        }
        &:last-child {
          &::after {
            content: '';
          }
        }
      }
    }
  }
  :deep(.ant-row) {
    // height: calc(100% - 54px - 16px);
    height: 100%;
    .ant-col {
      height: 100%;
    }
  }
  .box {
    position: relative;
    height: calc(100% - 54px - 14px);
    overflow: hidden;
    display: flex;
    flex-direction: column;
    padding: 12px;
    border-radius: 8px;
    border: 1px solid rgba(78, 117, 255, 0.4);
    background: linear-gradient(0deg, rgba(18, 38, 89, 0) -0.13%, rgba(11, 48, 120, 0.48) 99.87%);
    .radio {
      :deep(&.ant-radio-group) {
        height: 40px;
        min-height: 40px;
        .ant-radio-button-wrapper {
          height: 40px;
          min-height: 40px;
        }
      }
      .label {
        white-space: nowrap;
        color: var(---, #fff);
        text-align: center;
        /* 文字/06内文-标题 */
        font-family: Alibaba PuHuiTi 2;
        font-size: 12px;
        font-style: normal;
        font-weight: 600;
        line-height: 22px; /* 183.333% */
      }
      .num {
        color: var(---, #fff);
        text-align: center;
        font-family: Alibaba PuHuiTi 2;
        font-size: 12px;
        font-style: normal;
        font-weight: 400;
        line-height: 12px; /* 100% */
      }
    }
    .box-child {
      // height: calc((100% - 20px - 12px - 24px * 2) / 2);
      height: calc(100% - 20px - 24px);
    }
  }
  .box-header {
    height: 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 12px;
    .title {
      color: #297fff;
      font-family: Alibaba PuHuiTi 2;
      font-size: 14px;
      font-style: normal;
      font-weight: 600;
      line-height: 14px; /* 100% */
    }
    .right-value {
      display: flex;
      align-items: center;
      font-style: normal;
      .label {
        color: var(--unnamed, #fff);
        font-family: Alibaba PuHuiTi 2;
        font-size: 14px;
        font-weight: 400;
        line-height: 14px; /* 100% */
      }
      .value {
        color: #fff;
        font-family: DIN Alternate;
        font-size: 16px;
        font-weight: 700;
        line-height: 20px; /* 125% */
      }
    }
  }
  .small-row {
    height: calc(100% - 54px - 12px);
    .box {
      height: 100%;
      .box-header {
        justify-content: flex-start;
        .num {
          margin-left: 8px;
          color: #fff;
          font-size: 12px;
        }
      }
    }
    :deep(.ant-col) {
      height: calc((100% - 8px - 12px) / 2);
    }
    .box-child {
      height: calc(100% - 20px - 12px);
    }
  }
  .box-inventery-order {
    display: flex;
    flex-direction: column;
    gap: 12px;
    .inventery-order-title {
      color: var(---, #fff);
      font-family: Alibaba PuHuiTi 2;
      font-size: 16px;
      font-style: normal;
      font-weight: 400;
      line-height: normal;
      margin-bottom: 4px;
    }
    .box-item {
      position: relative;
      flex: 1;
      padding: 16px 12px;
      border-radius: 8px;
      border: 1px solid rgba(78, 117, 255, 0.4);
      background: linear-gradient(0deg, rgba(18, 38, 89, 0) -0.13%, rgba(11, 48, 120, 0.48) 99.87%);
    }
  }
  .flex {
    display: flex;
    align-items: center;
  }
}
</style>
